/**
 * AIOT智能学习桌 - 主程序
 * 目标平台: EBP3901开发板
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "../硬件适配层/hardware_abstraction.h"

// 系统状态定义
typedef enum {
    STATE_IDLE,
    STATE_LISTENING,
    STATE_PROCESSING,
    STATE_SPEAKING,
    STATE_MONITORING
} system_state_t;

// 坐姿监测数据
typedef struct {
    float current_distance;
    float optimal_min;
    float optimal_max;
    uint16_t alert_count;
    bool monitoring_active;
} posture_data_t;

// 语音交互数据
typedef struct {
    bool wake_word_detected;
    char last_command[128];
    char response_buffer[256];
    bool voice_active;
} voice_data_t;

// 学习数据记录
typedef struct {
    uint32_t session_start_time;
    uint32_t study_duration;
    uint16_t posture_alerts;
    uint16_t voice_interactions;
    float avg_distance;
    uint8_t focus_score;
} session_data_t;

// 全局变量
static system_state_t current_state = STATE_IDLE;
static posture_data_t posture_data = {35.0, 30.0, 50.0, 0, true};
static voice_data_t voice_data = {false, "", "", false};
static session_data_t session_data = {0, 0, 0, 0, 0.0, 85};

// 函数声明
void system_init(void);
void main_loop(void);
void handle_posture_monitoring(void);
void handle_voice_interaction(void);
void handle_system_state(void);
void update_session_data(void);
void display_system_status(void);

// 坐姿监测相关函数
bool check_posture_distance(void);
void trigger_posture_alert(const char* message);
void update_posture_data(float distance);

// 语音交互相关函数
bool detect_wake_word(void);
bool process_voice_command(void);
void generate_ai_response(const char* command);
void speak_response(const char* text);

// 工具函数
void format_time_string(uint32_t seconds, char* buffer);
void calculate_focus_score(void);

/**
 * 主函数
 */
int main(void) {
    printf("AIOT智能学习桌系统启动...\n");
    
    // 系统初始化
    system_init();
    
    // 显示启动信息
    oled_display_text(0, 0, "智能学习桌");
    oled_display_text(0, 16, "系统已启动");
    
    // LED指示系统启动
    led_blink(LED_BLUE_PIN, 3, 200);
    
    printf("系统初始化完成，进入主循环\n");
    
    // 主循环
    main_loop();
    
    return 0;
}

/**
 * 系统初始化
 */
void system_init(void) {
    // 硬件初始化
    hardware_init();
    
    // WiFi连接
    if (wifi_connect("YourWiFiSSID", "YourPassword")) {
        printf("WiFi连接成功\n");
        led_set(LED_GREEN_PIN, true);
    } else {
        printf("WiFi连接失败\n");
        led_set(LED_RED_PIN, true);
    }
    
    // 初始化会话数据
    session_data.session_start_time = system_get_tick();
    
    // 设置初始状态
    current_state = STATE_IDLE;
    
    printf("系统初始化完成\n");
}

/**
 * 主循环
 */
void main_loop(void) {
    uint32_t last_update_time = 0;
    uint32_t last_display_time = 0;
    
    while (1) {
        uint32_t current_time = system_get_tick();
        
        // 每100ms执行一次主要处理
        if (current_time - last_update_time >= 100) {
            handle_system_state();
            handle_posture_monitoring();
            handle_voice_interaction();
            update_session_data();
            
            last_update_time = current_time;
        }
        
        // 每5秒更新一次显示
        if (current_time - last_display_time >= 5000) {
            display_system_status();
            last_display_time = current_time;
        }
        
        // 检查按键
        if (button_is_pressed(BUTTON_FUNCTION_PIN)) {
            printf("功能按键按下\n");
            // 切换监测状态
            posture_data.monitoring_active = !posture_data.monitoring_active;
            system_delay_ms(200); // 防抖
        }
        
        if (button_is_pressed(BUTTON_CALIBRATION_PIN)) {
            printf("校准按键按下\n");
            // 校准当前距离为最佳距离
            float current_dist = ultrasonic_read_distance();
            posture_data.optimal_min = current_dist - 10.0;
            posture_data.optimal_max = current_dist + 10.0;
            buzzer_beep(1000, 200); // 确认音
            system_delay_ms(200); // 防抖
        }
        
        // 短暂延时
        system_delay_ms(10);
    }
}

/**
 * 处理系统状态
 */
void handle_system_state(void) {
    switch (current_state) {
        case STATE_IDLE:
            led_set(LED_BLUE_PIN, false);
            if (voice_data.wake_word_detected) {
                current_state = STATE_LISTENING;
                printf("状态切换: IDLE -> LISTENING\n");
            }
            break;
            
        case STATE_LISTENING:
            led_set(LED_BLUE_PIN, true);
            if (process_voice_command()) {
                current_state = STATE_PROCESSING;
                printf("状态切换: LISTENING -> PROCESSING\n");
            }
            break;
            
        case STATE_PROCESSING:
            generate_ai_response(voice_data.last_command);
            current_state = STATE_SPEAKING;
            printf("状态切换: PROCESSING -> SPEAKING\n");
            break;
            
        case STATE_SPEAKING:
            speak_response(voice_data.response_buffer);
            current_state = STATE_IDLE;
            voice_data.wake_word_detected = false;
            printf("状态切换: SPEAKING -> IDLE\n");
            break;
            
        case STATE_MONITORING:
            // 专门的监测状态
            break;
    }
}

/**
 * 处理坐姿监测
 */
void handle_posture_monitoring(void) {
    if (!posture_data.monitoring_active) {
        return;
    }
    
    // 读取距离
    float distance = ultrasonic_read_distance();
    update_posture_data(distance);
    
    // 检查坐姿
    if (!check_posture_distance()) {
        posture_data.alert_count++;
        session_data.posture_alerts++;
        
        if (distance < posture_data.optimal_min) {
            trigger_posture_alert("坐姿过近");
        } else if (distance > posture_data.optimal_max) {
            trigger_posture_alert("坐姿过远");
        }
    } else {
        // 坐姿正常，绿灯指示
        led_set(LED_GREEN_PIN, true);
        led_set(LED_RED_PIN, false);
    }
}

/**
 * 处理语音交互
 */
void handle_voice_interaction(void) {
    // 检测唤醒词
    if (!voice_data.wake_word_detected) {
        voice_data.wake_word_detected = detect_wake_word();
    }
}

/**
 * 检查坐姿距离
 */
bool check_posture_distance(void) {
    return (posture_data.current_distance >= posture_data.optimal_min &&
            posture_data.current_distance <= posture_data.optimal_max);
}

/**
 * 触发坐姿警报
 */
void trigger_posture_alert(const char* message) {
    printf("坐姿警报: %s (%.1fcm)\n", message, posture_data.current_distance);
    
    // LED警报
    led_set(LED_RED_PIN, true);
    led_set(LED_GREEN_PIN, false);
    
    // 蜂鸣器警报
    buzzer_beep(800, 200);
    
    // OLED显示
    char display_msg[32];
    snprintf(display_msg, sizeof(display_msg), "%s:%.1fcm", message, posture_data.current_distance);
    oled_display_text(0, 32, display_msg);
    
    // 每5次警报进行语音提示
    if (posture_data.alert_count % 5 == 0) {
        strncpy(voice_data.response_buffer, "请调整坐姿保持健康距离", sizeof(voice_data.response_buffer));
        speak_response(voice_data.response_buffer);
    }
}

/**
 * 更新坐姿数据
 */
void update_posture_data(float distance) {
    posture_data.current_distance = distance;
    
    // 更新平均距离
    static float distance_sum = 0;
    static uint16_t distance_count = 0;
    
    distance_sum += distance;
    distance_count++;
    session_data.avg_distance = distance_sum / distance_count;
}

/**
 * 检测唤醒词
 */
bool detect_wake_word(void) {
    // 简化的唤醒词检测
    // 实际实现需要音频处理和模式匹配
    uint16_t audio_sample = audio_read_sample();
    
    // 模拟检测逻辑（实际需要更复杂的算法）
    static uint16_t sample_count = 0;
    static uint32_t energy_sum = 0;
    
    energy_sum += (audio_sample > 2048) ? (audio_sample - 2048) : (2048 - audio_sample);
    sample_count++;
    
    if (sample_count >= 160) { // 10ms @ 16kHz
        uint32_t avg_energy = energy_sum / sample_count;
        sample_count = 0;
        energy_sum = 0;
        
        // 简单的能量阈值检测
        if (avg_energy > 100) {
            printf("检测到语音活动\n");
            return true;
        }
    }
    
    return false;
}

/**
 * 处理语音命令
 */
bool process_voice_command(void) {
    // 模拟语音识别
    // 实际实现需要调用语音识别API
    
    const char* commands[] = {
        "现在几点",
        "学习时长",
        "坐姿检查",
        "专注度",
        "休息提醒"
    };
    
    // 随机选择一个命令（模拟识别结果）
    static uint8_t cmd_index = 0;
    strncpy(voice_data.last_command, commands[cmd_index % 5], sizeof(voice_data.last_command));
    cmd_index++;
    
    printf("识别到命令: %s\n", voice_data.last_command);
    session_data.voice_interactions++;
    
    return true;
}

/**
 * 生成AI响应
 */
void generate_ai_response(const char* command) {
    // 简化的命令处理
    if (strstr(command, "几点")) {
        uint32_t current_time = system_get_tick() / 1000;
        uint32_t hours = (current_time / 3600) % 24;
        uint32_t minutes = (current_time / 60) % 60;
        snprintf(voice_data.response_buffer, sizeof(voice_data.response_buffer),
                "现在是%d点%d分", (int)hours, (int)minutes);
    }
    else if (strstr(command, "学习时长")) {
        uint32_t duration = session_data.study_duration / 60;
        snprintf(voice_data.response_buffer, sizeof(voice_data.response_buffer),
                "您已经学习了%d分钟", (int)duration);
    }
    else if (strstr(command, "坐姿")) {
        if (check_posture_distance()) {
            strcpy(voice_data.response_buffer, "您的坐姿很好请保持");
        } else {
            strcpy(voice_data.response_buffer, "请调整坐姿保持合适距离");
        }
    }
    else if (strstr(command, "专注度")) {
        calculate_focus_score();
        snprintf(voice_data.response_buffer, sizeof(voice_data.response_buffer),
                "您的专注度评分是%d分", session_data.focus_score);
    }
    else {
        strcpy(voice_data.response_buffer, "好的我明白了");
    }
}

/**
 * 语音播报
 */
void speak_response(const char* text) {
    printf("语音播报: %s\n", text);
    
    // 简化的语音合成（实际需要TTS引擎）
    // 这里用不同频率的蜂鸣器模拟
    for (int i = 0; text[i] != '\0'; i++) {
        uint16_t freq = 500 + (text[i] % 10) * 50;
        buzzer_beep(freq, 100);
        system_delay_ms(50);
    }
}

/**
 * 更新会话数据
 */
void update_session_data(void) {
    uint32_t current_time = system_get_tick();
    session_data.study_duration = (current_time - session_data.session_start_time) / 1000;
}

/**
 * 计算专注度评分
 */
void calculate_focus_score(void) {
    // 基于坐姿警报频率计算专注度
    uint32_t study_minutes = session_data.study_duration / 60;
    if (study_minutes > 0) {
        float alert_rate = (float)session_data.posture_alerts / study_minutes;
        session_data.focus_score = (uint8_t)(100 - (alert_rate * 10));
        if (session_data.focus_score > 100) session_data.focus_score = 100;
    }
}

/**
 * 显示系统状态
 */
void display_system_status(void) {
    char status_line1[32], status_line2[32], status_line3[32];
    
    // 第一行：距离和状态
    snprintf(status_line1, sizeof(status_line1), "距离:%.1fcm", posture_data.current_distance);
    
    // 第二行：学习时长
    uint32_t minutes = session_data.study_duration / 60;
    uint32_t seconds = session_data.study_duration % 60;
    snprintf(status_line2, sizeof(status_line2), "学习:%dm%ds", (int)minutes, (int)seconds);
    
    // 第三行：专注度
    calculate_focus_score();
    snprintf(status_line3, sizeof(status_line3), "专注度:%d分", session_data.focus_score);
    
    // 显示到OLED
    oled_display_text(0, 0, status_line1);
    oled_display_text(0, 16, status_line2);
    oled_display_text(0, 32, status_line3);
    
    // 控制台输出
    printf("=== 系统状态 ===\n");
    printf("距离: %.1fcm | 状态: %s\n", 
           posture_data.current_distance,
           check_posture_distance() ? "正常" : "异常");
    printf("学习时长: %dm%ds | 警报: %d次\n", 
           (int)minutes, (int)seconds, session_data.posture_alerts);
    printf("语音交互: %d次 | 专注度: %d分\n", 
           session_data.voice_interactions, session_data.focus_score);
    printf("================\n");
}